import { ref, onMounted, onBeforeUnmount, Ref } from 'vue'
import { fmtAmount } from '@/utils'
export const useAmountInput = (inputRef: Ref<HTMLInputElement | null>) => {
	const amount: any = ref(0)
	const focus = ref(false)

	const onKeydown = (event: KeyboardEvent) => {
		const { key } = event
		if (['Delete', 'Backspace', 'ArrowLeft', 'ArrowRight'].includes(key)) {
			return
		}
		const value = inputRef.value?.value
		let flag = false
		if (/[\d.]/.test(key)) {
			if (key === '.' && (value?.indexOf('.') !== -1 || value?.length === 0)) {
				flag = true
			}
		} else {
			flag = true
		}
		if (flag) {
			event.preventDefault()
		}
	}

	const onInput = () => {
		if (inputRef.value) {
			amount.value = +inputRef.value?.value
		}
	}

	const onFocus = () => {
		if (inputRef.value) {
			inputRef.value.value = (inputRef.value.value as string).replace(/\,/g, '')
			focus.value = true
			setTimeout(() => inputRef.value?.select())
		}
	}

	const onBlur = () => {
		focus.value = false
		setTimeout(() => {
			if (inputRef.value) {
				inputRef.value.value = fmtAmount(inputRef.value?.value, { hideCurrenySymbol: true })
			}
		})
	}

	onMounted(() => {
		inputRef.value?.addEventListener('keydown', onKeydown)
		inputRef.value?.addEventListener('input', onInput)
		inputRef.value?.addEventListener('focus', onFocus)
		inputRef.value?.addEventListener('blur', onBlur)
		if (inputRef.value) {
			inputRef.value.value = fmtAmount(inputRef.value?.value, { hideCurrenySymbol: true })
		}
	})

	onBeforeUnmount(() => {
		inputRef.value?.removeEventListener('keydown', onKeydown)
		inputRef.value?.removeEventListener('input', onInput)
		inputRef.value?.removeEventListener('focus', onFocus)
		inputRef.value?.removeEventListener('blur', onBlur)
	})

	return { amount, focus }
}
